package com.ruoyi.web.controller.system;

import java.io.IOException;
import java.util.List;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.ExceptionUtil;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.system.domain.SysFileInfo;
import com.ruoyi.system.domain.UDataPolicy;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.UDataStandard;
import com.ruoyi.system.service.IUDataStandardService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 标准台账Controller
 * 
 * @author ruoyi
 * @date 2024-05-10
 */
@Controller
@RequestMapping("/system/standard")
public class UDataStandardController extends BaseController
{
    private String prefix = "system/standard";

    @Autowired
    private IUDataStandardService uDataStandardService;

    @RequiresPermissions("system:standard:view")
    @GetMapping()
    public String standard()
    {
        return prefix + "/standard";
    }

    /**
     * 查询标准台账列表
     */
    @RequiresPermissions("system:standard:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(UDataStandard uDataStandard)
    {
        startPage();
        List<UDataStandard> list = uDataStandardService.selectUDataStandardList(uDataStandard);
        return getDataTable(list);
    }

    /**
     * 导出标准台账列表
     */
    @RequiresPermissions("system:standard:export")
    @Log(title = "标准台账", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(UDataStandard uDataStandard)
    {
        List<UDataStandard> list = uDataStandardService.selectUDataStandardList(uDataStandard);
        ExcelUtil<UDataStandard> util = new ExcelUtil<UDataStandard>(UDataStandard.class);
        return util.exportExcel(list, "标准台账数据");
    }

    /**
     * 新增标准台账
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存标准台账
     */
    @RequiresPermissions("system:standard:add")
    @Log(title = "标准台账", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(UDataStandard uDataStandard)
    {
        Long currentUser = ShiroUtils.getUserId();
        String name = uDataStandard.getName();
        if(!ObjectUtils.isEmpty(name)) {    // 去除名称两侧的空格
            name = name.trim();
        }
        if(ObjectUtils.isEmpty(name)){
            name = null;
        }
        uDataStandard.setName(name);

        String code = uDataStandard.getCode();
        if(ObjectUtils.isEmpty(code)) {     // 唯一索引不能为空串
            uDataStandard.setCode(null);
        }
        uDataStandard.setCreateUser(currentUser);

        try {
            return toAjax(uDataStandardService.insertUDataStandard(uDataStandard));
        } catch (Exception e) {
            String errorCode = ExceptionUtil.getErrorCode(e);
            if (errorCode.contains(ExceptionUtil.UNIQUE_ERROR)) {
                throw new RuntimeException("标准已存在，请检查...");
            }
            //否则的话，继续向外部抛出异常！
            throw e;
        }
    }

    /**
     * 修改标准台账
     */
    @RequiresPermissions("system:standard:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        UDataStandard uDataStandard = uDataStandardService.selectUDataStandardById(id);
        mmap.put("uDataStandard", uDataStandard);
        return prefix + "/edit";
    }

    /**
     * 修改保存标准台账
     */
    @RequiresPermissions("system:standard:edit")
    @Log(title = "标准台账", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(UDataStandard uDataStandard)
    {
        Long currentUser = ShiroUtils.getUserId();
        uDataStandard.setUpdateUser(currentUser);

        String name = uDataStandard.getName();
        if(!ObjectUtils.isEmpty(name)) {    // 去除名称两侧的空格
            name = name.trim();
        }
        if(ObjectUtils.isEmpty(name)){
            name = null;
        }
        uDataStandard.setName(name);

        String code = uDataStandard.getCode();
        if(ObjectUtils.isEmpty(code)) {     // 唯一索引不能为空串
            uDataStandard.setCode(null);
        }

        try {
            return toAjax(uDataStandardService.updateUDataStandard(uDataStandard));
        } catch (Exception e) {
            String errorCode = ExceptionUtil.getErrorCode(e);
            if (errorCode.contains(ExceptionUtil.UNIQUE_ERROR)) {
                throw new RuntimeException("标准已存在，请检查...");
            }
            //否则的话，继续向外部抛出异常！
            throw e;
        }
    }

    /**
     * 删除标准台账
     */
    @RequiresPermissions("system:standard:remove")
    @Log(title = "标准台账", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(uDataStandardService.deleteUDataStandardByIds(ids));
    }


    @PostMapping(value = "/upload")
    @ResponseBody
    public AjaxResult addSave(@RequestParam("file") MultipartFile file, Long id) throws IOException
    {
        String basePath = RuoYiConfig.getUploadPath();
        // 上传并返回新文件名称
        String filePath = FileUploadUtils.upload(basePath, file);
        return toAjax(uDataStandardService.updateUDataStandardFilePath(id, filePath));
    }


    @PostMapping(value = "/clearFile")
    @ResponseBody
    public AjaxResult clearFile(Long id) {
        UDataStandard uDataStandard = uDataStandardService.selectUDataStandardById(id);
        String filePath = uDataStandard.getFilePath();

        if(ObjectUtils.isEmpty(filePath)) {
            return success();
        }

        uDataStandardService.updateUDataStandardFilePath(id, null);
        String basePath = RuoYiConfig.getProfile();
        String file = basePath + filePath.substring("/profile".length());
        FileUtils.deleteFile(file);
        return success();
    }
}
